//
//  KY_WeiBoActionSheet.m
//  ShaQueVideo
//
//  Created by huliang on 13-4-30.
//  Copyright (c) 2013年 科悦信达. All rights reserved.
//

#import "KY_WeiBoActionSheet.h"
#import "KY_AppDelegate.h"
#import "KY_WriteWeiBoViewController.h"

@implementation KY_WeiBoActionSheet

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
    }
    return self;
}


-(void) layoutSubviews{
    
    [super layoutSubviews];
    
    CGRect frame;
    NSArray *nibArr = [[NSBundle mainBundle] loadNibNamed:@"KY_WeiBoActionSheet" owner:self options:nil];
    UIView *actionSheetView = [nibArr objectAtIndex:0];
    [self addSubview:actionSheetView];
    frame = actionSheetView.frame;
    UIButton *cancelBtn = (UIButton *)[actionSheetView viewWithTag:110];
    [cancelBtn addTarget:self action:@selector(dismiss:) forControlEvents:UIControlEventTouchUpInside];
    CGRect screenRect = [[UIApplication sharedApplication].keyWindow bounds];
    frame.origin.y = screenRect.size.height - frame.size.height ;
    
    UIButton *sinaBtn = (UIButton *)[actionSheetView viewWithTag:1];
    [sinaBtn addTarget:self action:@selector(sinaBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    
    [self setFrame:frame];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sinaweiboDidLogIn:) name:@"sinaweibo_didlogin" object:nil];
}

-(void)sinaBtnClicked{
    [self dismissWithClickedButtonIndex:0 animated:YES];
    KY_AppDelegate *appDelegate = (KY_AppDelegate *)[UIApplication sharedApplication].delegate;
//    [appDelegate.sinaweibo logOut];
    if (![appDelegate.sinaweibo isAuthValid]) {
        [appDelegate.sinaweibo logIn];
    }else{    //弹出写微博窗口
        KY_WriteWeiBoViewController *writeWeibo = [[KY_WriteWeiBoViewController alloc] initWithNibName:@"KY_WriteWeiBoViewController" bundle:nil];
        [appDelegate.tabBarController.selectedViewController presentModalViewController:writeWeibo animated:YES];
        [writeWeibo.textView becomeFirstResponder];
    }
    
    
}
-(void)dismiss:(id)sender{
    [self dismissWithClickedButtonIndex:0 animated:YES];
}

- (void)removeAuthData
{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"SinaWeiboAuthData"];
}

- (void)storeAuthData
{
    KY_AppDelegate *appDelegate = (KY_AppDelegate *)[UIApplication sharedApplication].delegate;
    SinaWeibo *sinaweibo = appDelegate.sinaweibo;
    NSDictionary *authData = [NSDictionary dictionaryWithObjectsAndKeys:
                              sinaweibo.accessToken, @"AccessTokenKey",
                              sinaweibo.expirationDate, @"ExpirationDateKey",
                              sinaweibo.userID, @"UserIDKey",
                              sinaweibo.refreshToken, @"refresh_token", nil];
    [[NSUserDefaults standardUserDefaults] setObject:authData forKey:@"SinaWeiboAuthData"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}


#pragma mark - SinaWeibo Delegate

- (void)sinaweiboDidLogIn:(SinaWeibo *)tmpSinaWeiBo
{
    NSLog(@"sinaweiboDidLogIn userID = %@ accesstoken = %@ expirationDate = %@ refresh_token = %@", tmpSinaWeiBo.userID, tmpSinaWeiBo.accessToken, tmpSinaWeiBo.expirationDate,tmpSinaWeiBo.refreshToken);
    [self storeAuthData];
}

- (void)sinaweiboDidLogOut:(SinaWeibo *)sinaweibo
{
    NSLog(@"sinaweiboDidLogOut");
    [self removeAuthData];
}

- (void)sinaweiboLogInDidCancel:(SinaWeibo *)sinaweibo
{
    NSLog(@"sinaweiboLogInDidCancel");
}

- (void)sinaweibo:(SinaWeibo *)sinaweibo logInDidFailWithError:(NSError *)error
{
    NSLog(@"sinaweibo logInDidFailWithError %@", error);
}

- (void)sinaweibo:(SinaWeibo *)sinaweibo accessTokenInvalidOrExpired:(NSError *)error
{
    NSLog(@"sinaweiboAccessTokenInvalidOrExpired %@", error);
    [self removeAuthData];
}

#pragma mark - SinaWeiboRequest Delegate

- (void)request:(SinaWeiboRequest *)request didFailWithError:(NSError *)error
{
    if ([request.url hasSuffix:@"users/show.json"])
    {
        [userInfo release], userInfo = nil;
    }
    else if ([request.url hasSuffix:@"statuses/user_timeline.json"])
    {
        [statuses release], statuses = nil;
    }
    else if ([request.url hasSuffix:@"statuses/update.json"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                            message:[NSString stringWithFormat:@"Post status failed!"]
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        
        NSLog(@"Post status failed with error : %@", error);
    }
    else if ([request.url hasSuffix:@"statuses/upload.json"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                            message:[NSString stringWithFormat:@"Post image status failed!"]
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        
        NSLog(@"Post image status failed with error : %@", error);
    }
    
    
}

- (void)request:(SinaWeiboRequest *)request didFinishLoadingWithResult:(id)result
{
    if ([request.url hasSuffix:@"users/show.json"])
    {
        [userInfo release];
        userInfo = [result retain];
    }
    else if ([request.url hasSuffix:@"statuses/user_timeline.json"])
    {
        [statuses release];
        statuses = [[result objectForKey:@"statuses"] retain];
    }
    else if ([request.url hasSuffix:@"statuses/update.json"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                            message:[NSString stringWithFormat:@"Post status \"%@\" succeed!", [result objectForKey:@"text"]]
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
    }
    else if ([request.url hasSuffix:@"statuses/upload.json"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                            message:[NSString stringWithFormat:@"Post image status \"%@\" succeed!", [result objectForKey:@"text"]]
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        
    }
}


@end
